var startDate;  //星期一时间
var endDate;    //星期天时间
var docStatus;  //医生状态
var docTime;    //对应时间
var doctorName; //医生名字
var doctorId; //医生ID
var state = ""; //判断是否点击 正常班 休息  按钮

var objTBs = document.getElementById("ArbetTable");
var objTBsd = document.getElementById("browseTable");

var tdDTs = new Date();
var tdDTsd = new Date();
var currDT;

function addDate(dt, num) {
    var ope = "+";
    if (num < 0) {
        ope = "-";
    }
    var reDT = dt;
    for (var i = 0; i < Math.abs(num); i++) {
        reDT = addOneDay(reDT, ope);
    }
    return reDT;
}

//增加或减少一天，由ope决定, + 为加，- 为减，否则不动
function addOneDay(dt, ope) {
    var num = 0;
    if (ope == "-") {
        num = -1;
    } else if (ope == "+") {
        num = 1;
    }
    var y = dt.getFullYear();
    var m = dt.getMonth();
    var lastDay = getLastDay(y, m);
    var d = dt.getDate();
    d += num;
    if (d < 1) {
        m--;
        if (m < 0) {
            y--;
            m = 11;
        }
        d = getLastDay(y, m);
    } else if (d > lastDay) {
        m++;
        if (m > 11) {
            y++;
            m = 0;
        }
        d = 1;
    }
    var reDT = new Date();
    reDT.setFullYear(y);
    reDT.setMonth(m, 1);
    reDT.setDate(d);

    return reDT;
}

//每月最后一天
function getLastDay(y, m) {
    var lastDay = 28;
    m++;
    if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
        lastDay = 31;
    } else if (m == 4 || m == 6 || m == 9 || m == 11) {
        lastDay = 30;
    } else if (isLeapYear(y) == true) {
        lastDay = 29;
    }
    return lastDay;
}

//是否为闰年
function isLeapYear(y) {
    var isLeap = false;
    if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
        isLeap = true;
    }
    return isLeap;
}


$(function () {
    schedulingSee();
    var scheduling_see = $("#scheduling_see>label");
    var scheduling_content = $("#scheduling_content>div");
    scheduling_see.eq(0).css({"border-bottom": "3px solid #2eadd0", "color": "#2eadd0"});
    scheduling_content.eq(0).show();
    scheduling_see.click(function () {
        $(this).css({"border-bottom": "3px solid #2eadd0", "color": "#2eadd0"}).siblings().css({
            "border": "none",
            "color": "inherit"
        });
        scheduling_content.eq(scheduling_see.index($(this))).show().siblings().hide()
    });
    var oldtdDTs = tdDTs;
    var oldtdDTsd = tdDTsd;
    $("#inputTime").change(function () {
        for (var i = 1; i < 8; i++) {
            objTBs.rows[0].cells[i].innerHTML = tdDTs.getFullYear() + '-' + (tdDTs.getMonth() + 1) + "-" + tdDTs.getDate();
            tdDTs = addDate(tdDTs, 1); //下一天
            oldtdDTs = tdDTs;
        }
    })
    $("#inputTimed").change(function () {
        for (var i = 1; i < 8; i++) {
            objTBs.rows[0].cells[i].innerHTML = tdDTsd.getFullYear() + '-' + (tdDTsd.getMonth() + 1) + "-" + tdDTsd.getDate();
            tdDTsd = addDate(tdDTsd, 1); //下一天
            oldtdDTsd = tdDTsd;
        }
    })
});

function schedulingSee() {
    $('#ArbetTable').bootstrapTable({
        method: "post",
        url: Feng.ctxPath + "/doctorLooked/findDoctorSchedulingList/",
        contentType: "application/x-www-form-urlencoded",
        queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
            var date = new Date();
            var currentWeek = date.getDay();
            var stepSunDay = -currentWeek + 1;
            if (currentWeek == 0) {
                stepSunDay = -7;
            }
            var stepMonday = 7 - currentWeek;
            var time = date.getTime();
            var monday = new Date(time + stepSunDay * 24 * 3600 * 1000);
            var sunday = new Date(time + stepMonday * 24 * 3600 * 1000);
            var weekTimeStartYear = monday.getFullYear();       // 当前年份
            var weekTimeStartMonth = monday.getMonth() + 1;    // 当前月份
            var weekTimeStartDay = monday.getDate()+1;         // 今日日期 几号
            if (weekTimeStartMonth < 10) weekTimeStartMonth = "0" + weekTimeStartMonth;
            if (weekTimeStartDay < 10) weekTimeStartDay = "0" + weekTimeStartDay;
            var weekTimeEndYear = sunday.getFullYear();       // 当前年份
            var weekTimeEndMonth = sunday.getMonth() + 1;    // 当前月份
            var weekTimeEndDay = sunday.getDate();         // 今日日期 几号
            if (weekTimeEndMonth < 10) weekTimeEndMonth = "0" + weekTimeEndMonth;
            if (weekTimeEndDay < 10) weekTimeEndDay = "0" + weekTimeEndDay;
            var outpatientName = $("#outpatientName", parent.document).val();
            startDate = weekTimeStartYear + "-" + weekTimeStartMonth + "-" + (weekTimeEndDay-6);
            endDate = weekTimeEndYear + "-" + weekTimeEndMonth + "-" + weekTimeEndDay;
            return {
                pageSize: params.limit, // 每页要显示的数据条数
                offset: params.offset, // 每页显示数据的开始行号
                sort: params.sort, // 要排序的字段
                sortOrder: params.order, // 排序规则
                startDate: startDate,// 额外添加的参数,
                endDate: endDate, // 额外添加的参数,
                outpatientName: outpatientName
            }
        },
        sortable: false,
        sidePagination: 'client',
        columns: [
            [
                {title: 'doctorId', field: 'doctorId', visible: false, align: 'center', valign: 'middle'},
                {
                    field: 'doctorName',
                    title: '<span style="display: inline-block;cursor:pointer;width: 19px;height: 20px;vertical-align: text-top;overflow: hidden" autocomplete="off" onclick="laydate({istiem:true,format:\'YYYY-MM-DD\',choose:checkDate})"><span id="ids" class="glyphicon glyphicon-calendar"></span></span>' +
                        '<span style="cursor:pointer" id="lastWeek"><span style="vertical-align: text-top;margin-right: 3px;" class="glyphicon glyphicon-backward"></span>上周</span>&nbsp;' +
                        '<span style="cursor:pointer" id="nestWeek">下周<span style="vertical-align: text-top;margin-left: 5px;" class="glyphicon glyphicon-forward"></span></span>',
                    align: 'center', valign: 'middle', sortable: true, width: "16%"
                },
                {field: 'MondayTime', title: '星期一时间', align: 'center', valign: 'middle', width: "12%"},
                {field: 'TuesdayTime', title: '星期二时间', align: 'center', valign: 'middle', width: "12%"},
                {field: 'WednesdayTime', title: '星期三时间', align: 'center', valign: 'middle', width: "12%"},
                {field: 'ThursdayTime', title: '星期四时间', align: 'center', valign: 'middle', width: "12%"},
                {field: 'FridayTime', title: '星期五时间', align: 'center', valign: 'middle', width: "12%"},
                {field: 'SaturdayTime', title: '星期六时间', align: 'center', valign: 'middle', width: "12%"},
                {field: 'SundayTime', title: '星期日时间', align: 'center', valign: 'middle', width: "12%"},
            ],
            [
                {title: 'doctorId', field: 'doctorId', visible: false, align: 'center', valign: 'middle'},
                {
                    field: 'doctorName',
                    title: '全部诊所',
                    align: 'center',
                    valign: 'middle',
                    width: "16%",
                    class: 'hide-num',
                    formatter: function (value, row, index) {
                        return "<p style='margin: 0;' class='" + row.doctorId + "'>" + value + "</p>";
                    }
                },
                {
                    field: 'mondayStatus',
                    title: '星期一',
                    align: 'center',
                    valign: 'middle',
                    width: "12%",
                    class: 'hide-num',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return "正常班";
                        } else if (value == '2') {
                            return "休息";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    field: 'tuesdayStatus',
                    title: '星期二',
                    align: 'center',
                    valign: 'middle',
                    width: "12%",
                    class: 'hide-num',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return "正常班";
                        } else if (value == '2') {
                            return "休息";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    field: 'wednesdayStatus',
                    title: '星期三',
                    align: 'center',
                    valign: 'middle',
                    width: "12%",
                    class: 'hide-num',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return "正常班";
                        } else if (value == '2') {
                            return "休息";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    field: 'thursdayStatus',
                    title: '星期四',
                    align: 'center',
                    valign: 'middle',
                    width: "12%",
                    class: 'hide-num',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return "正常班";
                        } else if (value == '2') {
                            return "休息";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    field: 'fridayStatus',
                    title: '星期五',
                    align: 'center',
                    valign: 'middle',
                    width: "12%",
                    class: 'hide-num',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return "正常班";
                        } else if (value == '2') {
                            return "休息";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    field: 'saturdayStatus',
                    title: '星期六',
                    align: 'center',
                    valign: 'middle',
                    width: "12%",
                    class: 'hide-num',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return "正常班";
                        } else if (value == '2') {
                            return "休息";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    field: 'sundayStatus',
                    title: '星期日',
                    align: 'center',
                    valign: 'middle',
                    width: "12%",
                    class: 'hide-num',
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return "正常班";
                        } else if (value == '2') {
                            return "休息";
                        } else {
                            return "";
                        }
                    }
                }
            ]
        ],
        height: $(window).height() - 120,
        onLoadSuccess: function () {
            showDate();
            getTdValue();
            reload()
        }
    });

    function getTdValue() {
        var tableId = document.getElementById("ArbetTable");
        for (var i = 1; i < tableId.rows.length; i++) {
            for (var x = 1; x < tableId.rows[0].cells.length; x++) {
                if (tableId.rows[i].cells[x].innerHTML.indexOf("休息") != -1) {
                    tableId.rows[i].cells[x].classList.add('tableBackground')
                }
            }
        }
    }


    var stime = document.getElementById("ids").innerHTML;
    if (stime == "" || stime == null) {
        currDT = new Date();
    } else {
        currDT = new Date(stime);
    }

    function showDate() {
        var objTB = document.getElementById("ArbetTable");
        var dw = currDT.getDay();
        var tdDT;
        //确定周一是那天
        if (dw == 0) {
            tdDT = addDate(currDT, -6);
        } else {
            tdDT = addDate(currDT, (1 - dw));
        }
        //在表格中显示一周的日期
        for (var i = 1; i < 8; i++) {
            objTB.rows[0].cells[i].innerHTML = tdDT.getFullYear() + '-' + (tdDT.getMonth() + 1) + "-" + tdDT.getDate();
            tdDT = addDate(tdDT, 1); //下一天
        }
    }

    //增加或减少若干天，由 num 的正负决定，正为加，负为减
    function addDate(dt, num) {
        var ope = "+";
        if (num < 0) {
            ope = "-";
        }
        var reDT = dt;
        for (var i = 0; i < Math.abs(num); i++) {
            reDT = addOneDay(reDT, ope);
        }
        return reDT;
    }

    //增加或减少一天，由ope决定, + 为加，- 为减，否则不动
    function addOneDay(dt, ope) {
        var num = 0;
        if (ope == "-") {
            num = -1;
        } else if (ope == "+") {
            num = 1;
        }
        var y = dt.getFullYear();
        var m = dt.getMonth();
        var lastDay = getLastDay(y, m);
        var d = dt.getDate();
        d += num;
        if (d < 1) {
            m--;
            if (m < 0) {
                y--;
                m = 11;
            }
            d = getLastDay(y, m);
        } else if (d > lastDay) {
            m++;
            if (m > 11) {
                y++;
                m = 0;
            }
            d = 1;
        }
        var reDT = new Date();
        reDT.setFullYear(y);
        reDT.setMonth(m, 1);
        reDT.setDate(d);
        return reDT;
    }

    //上一周
    $("#lastWeek").click(function () {
        var num = -7;
        currDT = addDate(currDT, num);
        showDate();
        startDate = $("#ArbetTable thead>tr").eq(0).children("th").eq(1).text();
        endDate = $("#ArbetTable thead>tr").eq(0).children("th").eq(7).text();
        var opt = {
            url: Feng.ctxPath + "/doctorLooked/findDoctorSchedulingList/",
            silent: true,
            type: "post",
            query: {
                "startDate": startDate,
                "endDate": endDate
            }
        };
        $("#ArbetTable").bootstrapTable('refresh', opt);
    });
    $("#nestWeek").click(function () {
        var num = 7;
        currDT = addDate(currDT, num);
        showDate();
        startDate = $("#ArbetTable thead>tr").eq(0).children("th").eq(1).text();
        endDate = $("#ArbetTable thead>tr").eq(0).children("th").eq(7).text();
        var opt = {
            url: Feng.ctxPath + "/doctorLooked/findDoctorSchedulingList/",
            silent: true,
            type: "post",
            query: {
                "startDate": startDate,
                "endDate": endDate
            }
        };
        $("#ArbetTable").bootstrapTable('refresh', opt);
    });

    //是否为闰年
    function isLeapYear(y) {
        var isLeap = false;
        if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
            isLeap = true;
        }
        return isLeap;
    }

    //每月最后一天
    function getLastDay(y, m) {
        var lastDay = 28;
        m++;
        if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
            lastDay = 31;
        } else if (m == 4 || m == 6 || m == 9 || m == 11) {
            lastDay = 30;
        } else if (isLeapYear(y) == true) {
            lastDay = 29;
        }
        return lastDay;
    }

    showDate();
}

$("#ArbetTable").on('click', 'td', function () {
    docStatus = "";
    doctorName = $(this).parent("tr").children("td.hide-num").eq(0).text();  //获取当前点击行的医生
    doctorId = $(this).parent("tr").children("td.hide-num").eq(0).children("p").attr('class');  //获取当前点击行的医生Id
    docTime = $("#ArbetTable thead>tr").eq(0).children("th").eq($(this).index()).text();  //获取当前点击对应的时间
    $("#ArbetTable > tbody > tr > td").removeClass('borders');
    if ($(this).index() == 0) {
        //选中整行
        if (state == "") {
            for (var i = 1; i <= $(this).nextAll('td').length; i++) {
                if (!$(this).parent("tr").children("td").eq(i).hasClass('prohibits')) { //判断是否小于当前时间
                    $(this).parent("tr").children("td").eq(i).addClass('borders');
                }
            }
        } else if (state == "rest") {  //如果等于休息
            docTime = "";
            docStatus = 2;
            doctorName = $(this).text();
            for (var e = 1; e <= $(this).nextAll('td').length; e++) {
                if (!$(this).parent("tr").children("td").eq(e).hasClass('prohibits')) { //判断是否小于当前时间
                    $(this).parent("tr").children("td").eq(e).addClass('borders tableBackground').html('休息');
                }
            }
            for (var t = 0; t < $('.borders').length; t++) {
                docTime += $("#ArbetTable thead>tr").eq(0).children("th").eq($('.borders').eq(t).index()).html() + ",";
            }
            $.ajax({
                url: Feng.ctxPath + "/doctorLooked/updateStatus/",
                type: "post",
                data: {
                    "doctorName": doctorName,
                    "doctorId": doctorId,
                    "docTime": docTime,
                    "docStatus": docStatus
                },
                success: function (data) {

                },
                error: function (data) {
                    alert("错误");
                }
            });
        } else if (state == "normal") { //如果等于正常班
            docTime = "";
            docStatus = 1;
            doctorName = $(this).text();
            for (var a = 1; a <= $(this).nextAll('td').length; a++) {
                if (!$(this).parent("tr").children("td").eq(a).hasClass('prohibits')) { //判断是否小于当前时间
                    $(this).parent("tr").children("td").eq(a).addClass('borders').html('正常班').removeClass('tableBackground');
                }
            }
            for (var w = 0; w < $('.borders').length; w++) {
                docTime += $("#ArbetTable thead>tr").eq(0).children("th").eq($('.borders').eq(w).index()).html() + ",";
            }
            $.ajax({
                url: Feng.ctxPath + "/doctorLooked/updateStatus/",
                type: "post",
                data: {
                    "doctorName": doctorName,
                    "doctorId": doctorId,
                    "docTime": docTime,
                    "docStatus": docStatus
                },
                success: function (data) {

                },
                error: function (data) {
                    alert("错误");
                }
            });
        }

    } else {     //选中单个

        if (state == "") {
            $(this).addClass('borders');
        } else if (state == "rest") {  //如果等于休息
            $(this).addClass('tableBackground borders').html("休息");
            docStatus = 2;
            $.ajax({
                url: Feng.ctxPath + "/doctorLooked/updateStatus/",
                type: "post",
                data: {
                    "doctorName": doctorName,
                    "doctorId": doctorId,
                    "docTime": docTime,
                    "docStatus": docStatus
                },
                success: function (data) {

                },
                error: function (data) {
                    alert("错误");
                }
            });
        } else if (state == "normal") { //如果等于正常班
            $(this).removeClass('tableBackground').html("正常班").addClass('borders');
            docStatus = 1;
            $.ajax({
                url: Feng.ctxPath + "/doctorLooked/updateStatus/",
                type: "post",
                data: {
                    "doctorName": doctorName,
                    "doctorId": doctorId,
                    "docTime": docTime,
                    "docStatus": docStatus
                },
                success: function (data) {

                },
                error: function (data) {
                    alert("错误");
                }
            });
        }
    }
});

//点击休息
$('#rest').click(function () {
    docTime = "";   //初始化时间
    docStatus = ""; //初始化状态
    doctorName = "";//初始化医生
    doctorId = "";
    if (state == "rest") {  //如果已经是休息状态则返回初始
        state = "";
        $('#rest').css({"background": "#A9A9A9", "border": "2px solid #999999", "color": "#4f4f4f"})
    } else {  //否则给他加上变量
        state = "rest";
        $("#normal").css({"background": "none", "border": "2px solid #999999", "color": "#4f4f4f"});
        $('#rest').css({"background": "#2eadd0", "border": "2px solid #2eadd0", "color": "#ffffff"});
        //给选中的改变样式
        $('.borders').addClass('tableBackground').html("休息");
        if ($('.borders').length == 0) {
            return;  //如果没有选中的就 return 出去
        } else {
            docStatus = 2;  //状态赋值
            doctorName = $('.borders').parent("tr").children("td.hide-num").eq(0).text();  //获取选中行的医生
            doctorId = $('.borders').parent("tr").children("td.hide-num").eq(0).children("p").attr('class');  //获取当前点击行的医生Id
            for (var i = 0; i < $('.borders').length; i++) {
                //获取选中对应的时间
                docTime += $("#ArbetTable thead>tr").eq(0).children("th").eq($('.borders').eq(i).index()).html() + ",";
            }
            $.ajax({
                url: Feng.ctxPath + "/doctorLooked/updateStatus/",
                type: "post",
                data: {
                    "doctorName": doctorName,
                    "doctorId": doctorId,
                    "docTime": docTime,
                    "docStatus": docStatus
                },
                success: function (data) {

                },
                error: function (data) {
                    alert("错误");
                }
            });
        }
    }
});

//点击正常班
$("#normal").click(function () {
    docTime = "";   //初始化时间
    docStatus = ""; //初始化状态
    doctorName = "";//初始化医生
    doctorId = "";
    if (state == "normal") {  //如果已经是正常班状态则返回初始
        state = "";
        $("#normal").css({"background": "none", "border": "2px solid #999999", "color": "#4f4f4f"})
    } else {     //否则给他加上变量
        state = "normal";
        $('#rest').css({"background": "#a9a9a9", "border": "2px solid #999999", "color": "#4f4f4f"});
        $("#normal").css({"background": "#2eadd0", "border": "2px solid #2eadd0", "color": "#ffffff"});
        //给选中的改变样式
        $(".borders").removeClass('tableBackground').html("正常班");
        if ($('.borders').length == 0) {
            return;  //如果没有选中的就 return 出去
        } else {
            docStatus = 1;  //状态赋值
            doctorName = $('.borders').parent("tr").children("td.hide-num").eq(0).text();  //获取选中行的医生
            doctorId = $('.borders').parent("tr").children("td.hide-num").eq(0).children("p").attr('class');  //获取当前点击行的医生Id
            for (var i = 0; i < $('.borders').length; i++) {
                //获取选中对应的时间
                docTime += $("#ArbetTable thead>tr").eq(0).children("th").eq($('.borders').eq(i).index()).html() + ",";
            }
            $.ajax({
                url: Feng.ctxPath + "/doctorLooked/updateStatus/",
                type: "post",
                data: {
                    "doctorName": doctorName,
                    "doctorId": doctorId,
                    "docTime": docTime,
                    "docStatus": docStatus
                },
                success: function (data) {
                },
                error: function (data) {
                    alert("错误");
                }
            });
        }
    }
});

function reload() {
    var timeDate = new Date();
    var year = timeDate.getFullYear();
    var month = timeDate.getMonth() + 1;
    var strDate = timeDate.getDate();
    var time = year + '-' + month + '-' + strDate;
    var tableId = document.getElementById("ArbetTable");
    for (var i = 1; i < 8; i++) {
        var a = $("#ArbetTable thead>tr:eq(0)").children("th")[i].innerHTML;
        if (new Date(a).getTime() < new Date(time).getTime()) {
            for (var e = 0; e < tableId.rows.length; e++) {
                tableId.rows[e].cells[i].classList.add("prohibit", "prohibits");
            }
        }
        // if(new Date(a).getTime() == new Date(time).getTime()){
        //     for (var w = 0; w < tableId.rows.length; w++) {
        //         tableId.rows[w].cells[i].className = "prohibits";
        //     }
        // }
    }
}


function checkDate() {
    var stime = document.getElementById("ids").innerHTML;
    if (stime == "" || stime == null) {
        currDT = new Date();
    } else {
        currDT = new Date(stime);
    }

    function showDates() {
        var dw = currDT.getDay();
        //确定周一是那天
        if (dw == 0) {
            tdDTs = addDate(currDT, -6);
        } else {
            tdDTs = addDate(currDT, (1 - dw));
        }
        document.getElementById("inputTime").value = tdDTs;
        for (var i = 1; i < 8; i++) {
            objTBs.rows[0].cells[i].innerHTML = tdDTs.getFullYear() + '-' + (tdDTs.getMonth() + 1) + "-" + tdDTs.getDate();
            tdDTs = addDate(tdDTs, 1); //下一天
        }
        startDate = $("#ArbetTable thead>tr").eq(0).children("th").eq(1).text();
        endDate = $("#ArbetTable thead>tr").eq(0).children("th").eq(7).text();
        var opt = {
            url: Feng.ctxPath + "/doctorLooked/findDoctorSchedulingList/",
            silent: true,
            type: "post",
            query: {
                "startDate": startDate,
                "endDate": endDate
            }
        };
        $("#ArbetTable").bootstrapTable('refresh', opt);
    }

    //增加或减少若干天，由 num 的正负决定，正为加，负为减
    function addDate(dt, num) {
        var ope = "+";
        if (num < 0) {
            ope = "-";
        }
        var reDT = dt;
        for (var i = 0; i < Math.abs(num); i++) {
            reDT = addOneDay(reDT, ope);
        }
        return reDT;
    }

    //增加或减少一天，由ope决定, + 为加，- 为减，否则不动
    function addOneDay(dt, ope) {
        var num = 0;
        if (ope == "-") {
            num = -1;
        } else if (ope == "+") {
            num = 1;
        }
        var y = dt.getFullYear();
        var m = dt.getMonth();
        var lastDay = getLastDay(y, m);
        var d = dt.getDate();
        d += num;
        if (d < 1) {
            m--;
            if (m < 0) {
                y--;
                m = 11;
            }
            d = getLastDay(y, m);
        } else if (d > lastDay) {
            m++;
            if (m > 11) {
                y++;
                m = 0;
            }
            d = 1;
        }
        var reDT = new Date();
        reDT.setFullYear(y);
        reDT.setMonth(m, 1);
        reDT.setDate(d);
        return reDT;
    }

    //是否为闰年
    function isLeapYear(y) {
        var isLeap = false;
        if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
            isLeap = true;
        }
        return isLeap;
    }

    //每月最后一天
    function getLastDay(y, m) {
        var lastDay = 28;
        m++;
        if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
            lastDay = 31;
        } else if (m == 4 || m == 6 || m == 9 || m == 11) {
            lastDay = 30;
        } else if (isLeapYear(y) == true) {
            lastDay = 29;
        }
        return lastDay;
    }

    showDates();
}